package com.zzyl.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.support.json.JSONParser;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonParser;
import com.zzyl.base.PageBean;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.service.*;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MemberServiceImpl implements MemberService {

    private static final List<String> DEFAULT_NICKNAME_PREFIX =
            List.of("生活更美好", "大桔大利", "日富一日", "好柿开花", "柿柿如意", "一椰暴富", "大柚所为", "杨梅吐气", "天生荔枝");

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private ContractService contractService;
    @Autowired
    private MemberElderService memberElderService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private WechatService wechatService;
    @Autowired
    JwtTokenProperties jwtTokenProperties;

    /**
     * 根据id查询用户
     *
     * @param id 用户id
     * @return 用户信息
     */
    @Override
    public Member getById(Long id) {
        return memberMapper.selectById(id);
    }

    /**
     * 分页查询用户列表
     *
     * @param page     当前页码
     * @param pageSize 每页数量
     * @param phone    手机号
     * @param nickname 昵称
     * @return 分页结果
     */
    @Override
    public PageBean<MemberVo> page(Integer page, Integer pageSize, String phone, String nickname) {
        PageHelper.startPage(page, pageSize);
        Page<Member> listPage = memberMapper.page(phone, nickname);

        PageBean<MemberVo> pageBean = PageBean.of(listPage, MemberVo.class);

        pageBean.getRecords().forEach(memberVo -> {
            List<ContractVo> contractVos = contractService.listByMemberPhone(memberVo.getPhone());
            memberVo.setIsSign(contractVos.isEmpty() ? "否" : "是");
            List<OrderVo> orderVos = orderService.listByMemberId(memberVo.getId());
            memberVo.setOrderCount(orderVos.size());
            List<MemberElderVo> memberElderVos = memberElderService.listByMemberId(memberVo.getId());
            List<String> collect = memberElderVos.stream().map(m -> m.getElderVo().getName()).collect(Collectors.toList());
            memberVo.setElderNames(String.join(",", collect));
        });
        return pageBean;
    }

    @Override
    public WxLoginVo login(UserLoginRequestDto dto) {
      /*  Map<String, Object> map = new HashMap<>();
        map.put("appid", "wx90c0a5c44c7d1e99");
        map.put("secret", "65b8a2bf7e23b9c62f4094db8db6a96d");
        map.put("grant_type", "authorization_code");
        map.put("js_code", dto.getCode());
        HttpResponse execute = HttpUtil.createGet("https://api.weixin.qq.com/sns/jscode2session")
                .form(map)
                .execute();
        String body = execute.body();
        String openid = JSONObject.parseObject(body).getString("openid");*/
        String openid = wechatService.getOpenid(dto.getCode());
        String phone = wechatService.getPhone(dto.getPhoneCode());

        /*if (StrUtil.isBlank(openid)) {
            throw new RuntimeException(JSONObject.parseObject(openid).getString("errmsg"));
        }*/

        Member byOpenId = memberMapper.getByOpenId(openid);
        if (ObjectUtil.isEmpty(byOpenId)) {
            String nickName = RandomUtil.randomEle(DEFAULT_NICKNAME_PREFIX) + RandomUtil.randomNumbers(4);

            byOpenId = new Member();
            byOpenId.setName(nickName);
            byOpenId.setPhone(phone);
            byOpenId.setOpenId(openid);
            memberMapper.save(byOpenId);
        }

        Map<String, Object> map1 = new HashMap<>();
        map1.put("id",byOpenId.getId());
        String jwt = JwtUtil.createJWT(jwtTokenProperties.getSecretKey(), jwtTokenProperties.getTtl(), map1);
        return WxLoginVo.builder().nickName(byOpenId.getName()).token(jwt).build();
    }
}
